<template>
  <Transition name="fade">
    <div v-if="value" class="action-sheet" @click.self="handleMask">
      <div class="action-sheet__body">
        <div
          class="action-sheet__item"
          v-for="(item, index) in actions"
          :key="index"
          @click="handleClick(item)"
        >
          {{ item.name }}
        </div>

        <div
          v-if="cancelText"
          class="action-sheet__cancel"
          @click="handleCancel"
        >
          {{ cancelText }}
        </div>
      </div>
    </div>
  </Transition>
</template>

<script>
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    actions: {
      type: Array,
      default: () => [],
    },
    // 是否在点击选项自己自动关闭
    closeOnClickAction: {
      type: Boolean,
      default: false,
    },
    // 是否在点击蒙层之后自动关闭
    closeOnClickOverlay: {
      type: Boolean,
      default: true,
    },
    cancelText: {
      type: String,
      default: "",
    },
  },

  methods: {
    close() {
      this.$emit("input", false);
    },
    handleClick(item) {
      // 触发自定义的 select
      this.$emit("select", item);

      // 判断 closeOnClickAction 是否为true
      if (this.closeOnClickAction) {
        // 主动关闭
        // this.$emit("input", false);
        this.close();
      }
    },

    handleCancel() {
      // 关闭
      // this.$emit("input", false);
      this.close();
      // 还要触发一个 cancel 自定义事件
      this.$emit("cancel");
    },

    handleMask() {
      // 判断 this.closeOnClickOverlay 是否为 true
      if (this.closeOnClickOverlay) {
        this.close();
      }
    },
  },
};
</script>

<style scoped>
.action-sheet {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
}

.action-sheet__body {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  /* height: 100px; */
  padding: 10px 0;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  background-color: #fff;
  transition: transform 0.5s ease;
}

.action-sheet__item,
.action-sheet__cancel {
  height: 44px;
  line-height: 44px;
  text-align: center;
  user-select: none;
  cursor: pointer;
}

.action-sheet__cancel::before {
  content: "";
  display: block;
  height: 10px;
  background-color: aquamarine;
}

.action-sheet__item:active {
  background-color: #ccc;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter .action-sheet__body,
.fade-leave-to .action-sheet__body {
  /* height: 0; */
  transform: translate3d(0, 100%, 0);
}
</style>
